package com.msgqu.share.utils;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;

/**
 * @description:
 * @author: wsj
 * @create: 2020-11-14 20:17
 * @throws:
 */
public class RedisUtil {

    /**
     * @description: 设置String类型
     * @params: [key, value]
     * @return: void
     * @author: wsj
     * @create: 2020-11-14 20:25
     * @throws
     */
    public static void setString(String key,String value){
        getRedisTemplate().opsForValue().set(key,value);
    }
    /**
     * @description: 获取String类型数据
     * @params: [key]
     * @return: java.lang.Object
     * @author: wsj
     * @create: 2020-11-14 20:29
     * @throws
     */
    public static String getString(String key){
        if(StringUtils.isNotBlank(key)){
            return (String) getRedisTemplate().opsForValue().get(key);
        }
        return null;
    }
    /**
     * @description: 判断key是否存在
     * @params: [key]
     * @return: boolean
     * @author: wsj
     * @create: 2020-11-15 16:41
     * @throws
     */
    public static boolean hashKey(String key){
        return getRedisTemplate().hasKey(key);
    }

    /**
     * @description: 设置hash类型value值
     * @params: [key, map]
     * @return: void
     * @author: wsj
     * @create: 2020-11-14 21:19
     * @throws
     */
    public static void hashPutAll(String key, Map map) {
        getRedisTemplate().opsForHash().putAll(key,map);
    }
    /**
     * @description: 根据key获取整个hash数据
     * @params: [key]
     * @return: java.util.Map<java.lang.Object,java.lang.Object>
     * @author: wsj
     * @create: 2020-11-15 16:22
     * @throws
     */
    public static Map<Object,Object> hashEntries(String key){
        return getRedisTemplate().opsForHash().entries(key);
    }

    /**
     * @description: 获取redisTemplate
     * @return: org.springframework.data.redis.core.RedisTemplate
     * @author: wsj
     * @create: 2020-11-14 20:20
     * @throws
     */
    public static RedisTemplate getRedisTemplate(){
        return ApplicationContextHelper.getBeanByBeanName("redisTemplate");
    }

    /**
     * @description: 获取redisson
     * @params: []
     * @return: org.redisson.Redisson
     * @author: wsj
     * @create: 2020-11-15 12:36
     * @throws
     */
    public static Redisson getRedisson(){
        return ApplicationContextHelper.getBeanByType(Redisson.class);
    }
    /**
     * @description: 获取redis分布式锁
     * @params: [name]
     * @return: org.redisson.api.RLock
     * @author: wsj
     * @create: 2020-11-15 12:34
     * @throws
     */
    public static RLock getLock(String name){
        return getRedisson().getLock(name);
    }
    /**
     * @description: 解锁
     * @params: [rLock]
     * @return: void
     * @author: wsj
     * @create: 2020-11-15 12:34
     * @throws
     */
    public static void unLock(RLock rLock){
        rLock.unlock();
    }
}
